import { Card,Button,Table,Image,Modal, Form, Input,Upload,message,Popconfirm } from 'antd';
import { PlusOutlined,EditOutlined,DeleteOutlined,LoadingOutlined } from '@ant-design/icons';
import type { ColumnsType } from 'antd/es/table';
import React from 'react';
import './index.less'
import { getTrademarkPageListApi, saveTrademarkApi, updateTrademarkApi,deleteTrademarkApi } from '@/api/product/trademark'
import { TrademarkModel,TrademarkListModel } from '@/api/product/model/trademark'
import { useEffect, useState,useRef } from 'react'
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';

const Trademark: React.FC = () =>{
    /* 声明状态----------------------------------------------------------------- */
    // 品牌列表
    const [TrademarkList, setTrademarkList] = useState<TrademarkListModel>([])
    // 当前页码
    const [current, setCurrent] = useState(1)
    // 每页条数
    const [pageSize, setPageSize] = useState(3)
    // 总共
    const [total, setTotal] = useState(0)
    // 控制显示添加和编辑的Modal标识
    const [isShowAddOrUpdateModal,setisShowAddOrUpdateModal] = useState(false)
    // 图片上传的loading效果显示的标识
    const [loading, setLoading] = useState(false);
    // 图片上传的图片路径
    const [imageUrl, setImageUrl] = useState<string>();
    // 添加图片上传的路径
    const [postImageUrl,setPostImageUrl]=useState<string>()
    // // const postImageUrlRef=useRef<string>() // imageUrl的动态引用
    // // 添加或者修改的品牌名称
    const [postTmName,setPostTmName]=useState<string>()
    // 判断点击的是添加还是修改的标识
    const [isClickAdd,setIsClickAdd]=useState(false)    


    const [xid,setXid]=useState(0)
    // let isClickAdd = false
    // const [form_add_update,set_form_add_update]=useState({tmName:'',logoUrl:''})
    // let form_add_update = {id:0,tmName:'',logoUrl:''}
    /* 声明状态----------------------------------------------------------------- */

    // 上传图片的路径前缀
    const uploadUrl=process.env.REACT_APP_UPLOAD_API


    
    // 请求品牌分页列表的函数
    async function  getTrademarkList(currentPage=current,limit=pageSize){
        // 发送请求
        const result = await getTrademarkPageListApi(currentPage,limit)
        // 将请求回来的records数据赋值给TrademarkList
        setTrademarkList(result.records)
        // console.log(result)
        // cuurent、pagesize、total重新赋值
        setCurrent(result.current)
        setPageSize(result.size)
        setTotal(result.total)
    }

    useEffect(() => {
        // 挂载的时候请求数据
        getTrademarkList();
    }, []);

    // 显示添加和编辑的Modal
   const toShowAddOrUpdateModal=(row:any)=>{
        // 对形参进行数据处理
        form.setFieldsValue(row)
        // 给ImageUrl重新赋值
        setImageUrl(row.logoUrl)
        // 重新拿值
        setPostTmName(row.tmName)
        // 判断是否有id，如果有，则为修改，如果没有则为添加
        if(row.id){
            // 更改isClickAdd的值
            setIsClickAdd(false)
        }else{
            setIsClickAdd(true)
        }
        // console.log('打开了Modal',id)
        setisShowAddOrUpdateModal(true)
        // console.log(form_add_update);
        console.log(isClickAdd)
        setXid(row.id)
        console.log(imageUrl,'判断add');
        
    }

    // 点击Modal的确定按钮的函数
    async function ModalOk(){
        // 获取输入框的值
        const tmName=tmNameValue
        // console.log(xid,tmName,imageUrl);
        
        // 通过判断标识，确定是添加还是修改
        if(isClickAdd){
            // console.log('添加');
            // 发送添加请求
            await saveTrademarkApi(tmName as string,imageUrl as string)
            // 提示
            message.success('添加成功')
        }else{
            // console.log('修改');
            // 发送修改请求
            await updateTrademarkApi(xid as number,tmName as string,imageUrl as string)
            // 提示
            message.success('修改成功')
        }
        setisShowAddOrUpdateModal(false)

        // 重新获取数据
        getTrademarkList();

        console.log(imageUrl,'成功add');
    }

    // 关闭添加和编辑的Modal
    function cancelAddOrUpdateModal(){
        // console.log('关闭了Modal')
        // 关闭Modal
        setisShowAddOrUpdateModal(false)
        // 重置图片
        setImageUrl('')
    }


    // 删除品牌
    const deleteTrademark=async(row:any)=>{
        // console.log(row);
        // 发起删除请求
        await deleteTrademarkApi(row.id)
        // 提示
        message.success('删除成功!')
        // 重新获取数据
        getTrademarkList()
    }

    // 取消删除提示关闭
    const CancelDelConfirm=()=>{
        // 提示
        message.error('取消删除!');
    }



    // 


    /* 图片上传---------------------------------------------------------------------------- */
    const beforeUpload = (file: RcFile) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
          message.error('只支持上传jpg/png格式的图片哦!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
          message.error('图片大小不能超过2MB哦!');
        }
        return isJpgOrPng && isLt2M;
    };


    const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
        if (info.file.status === 'uploading') {
          setLoading(true);
          console.log('cl',info);
          
          return;
        }
        console.log(info.fileList[0].response.data,22222)

        if (info.file.status === 'done') {
          getBase64(info.file.originFileObj as RcFile, (url) => {
            setLoading(false);
            // 将上传后的响应回来的数据的图片地址存放起来
            setImageUrl(info.fileList[0].response.data);
            console.log(info.fileList[0].response.data,'存地址');
          });
        }
    };

    
    const getBase64 = (img: RcFile, callback: (url: string) => void) => {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result as string));
        reader.readAsDataURL(img);
    };


    // 上传组件
    const uploadButton = (
        <div>
          {loading ? <LoadingOutlined /> : <PlusOutlined />}
          <div style={{ marginTop: 8 }}>点击上传</div>
        </div>
    );
    /* 图片上传---------------------------------------------------------------------------- */


    // 表单
    const [form] = Form.useForm<{ tmName: string; logoUrl: string }>();
    const tmNameValue = Form.useWatch('tmName', form);
    // const logoUrlValue = Form.useWatch('logoUrl',form)

      

    // table表格的列模板
    const columns:ColumnsType<any> = [
      {
        align: 'center',
        title:'序号',
        width:100,
        render(value, row, index) {
            return index + 1
        },
      },
      {
        title: '品牌名称',
        dataIndex: 'tmName',
        key: 'tmName',
      },
      {
        title: '品牌LOGO',
        dataIndex:"logoUrl",
        key:'logoUrl',
        render(logoUrl: string){
          return(
              <>
                  <Image
                      width={100}
                      src={logoUrl}
                  />
              </>
          )
      }
      },
      {
        title: '操作',
        key:'1',
        render(row){
          return(
              <>
                <Button type="primary" className='btn_edit' onClick={()=>toShowAddOrUpdateModal(row)} icon={<EditOutlined/>} />
                <Popconfirm
                      title={`确定要删除${row.tmName}吗?`}
                      onConfirm={()=>deleteTrademark(row)} 
                      onCancel={CancelDelConfirm}
                      okText="确定"
                      cancelText="取消"
                    >
                      <Button type="primary" className='btn_delete' danger icon={<DeleteOutlined/>} />
                    </Popconfirm>
                
              </>
          )
        }
      },
    ];
    return(
        <div>
            <Card className='trademark_card' bordered={false} style={{ width: 1720,height:600 }}>
                <Card style={{width:1720,marginLeft:-24,marginTop:-24}}>
                    <Button icon={<PlusOutlined />} type="primary" onClick={()=>toShowAddOrUpdateModal({id:0,tmName:'',logoUrl:''})}>添加</Button>
                </Card>
                <Table rowKey='id' dataSource={TrademarkList} columns={columns} bordered pagination={{
                    current,
                    total,
                    pageSize,
                    showSizeChanger: true,
                    pageSizeOptions: [3, 6, 9],
                    showQuickJumper: true,
                    showTotal: (total) => `总共${total}条`,
                    // onChange: 当页码更新或者数量更新，会重新执行
                    onChange: getTrademarkList,
                }} />
            </Card>
            
            <Modal 
                width={950} 
                bodyStyle={{height:350}} 
                className="AddOrUpdate_Modal"  
                title={isClickAdd?'添加品牌':'修改品牌' }
                visible={isShowAddOrUpdateModal} 
                onOk={ModalOk} 
                onCancel={cancelAddOrUpdateModal}>
                <Form
                  form={form}
                  labelCol={{ span: 8 }}
                  wrapperCol={{ span: 16 }}
                  style={{ maxWidth: 600 }}
                  initialValues={{ remember: true }}
                  autoComplete="off"
                  name="form"
                //   onFinish={ModalOk}
                >
                    <Form.Item
                        label="品牌名称"
                        name="tmName"
                        rules={[{ required: true, message: '品牌名称是必填项哦!' }]}
                    >
                        <Input  /> 
                    </Form.Item>
                    {/* <a>{logoUrlValue}</a> */}
                    {/* <a>{{postTmName}}</a>
                    <a>{{postImageUrl}}</a> */}
                    {/* <a>{postTmName}</a> */}
                    <Form.Item 
                        label="品牌LOGO"
                        name="logoUrl"
                        rules={[{ required: true, message: '品牌LOGO是必选项哦!' }]}
                    >
                       <Upload
                           name="file"
                           listType="picture-card"
                           className="avatar-uploader"
                           showUploadList={false}
                           action={`${uploadUrl}/admin/product/fileUpload`}
                           beforeUpload={beforeUpload}
                           onChange={handleChange}
                         >
                           {imageUrl ? <img src={imageUrl} alt="avatar" style={{ width: '100%' }} /> : uploadButton}
                        </Upload>  
                    </Form.Item>
                </Form>
            </Modal>
        </div>
    )
}

export default Trademark